package com.ruoyi.auth.controller;

import com.ruoyi.auth.form.RegisterBody;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginUser;
import com.stylefeng.sso.plugin.constants.SsoConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * token 控制  TODO 重写了登录逻辑和退出逻辑
 * 
 * @author ruoyi
 */
@RestController
public class TokenController
{

    private Logger log = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    /**
     * 通过sso服务器传递过来的token认证的方法；
     * @param gunsToken
     * @param request
     * @return
     */
    @GetMapping("/")
    public R<?> login(@RequestParam("gunsToken") String gunsToken, HttpServletRequest request){
        // 用户登录
        HttpSession session = request.getSession();
        // 这里也是需要判断一下这个地方有没值的
        Long id = (Long)session.getAttribute(SsoConstants.LOGIN_USER_ID);
        if (id == null) {
            log.info("这个地方出现问题");
            return R.fail();
        }
        LoginUser userInfo = sysLoginService.getUserInfo(id);
        return R.ok(tokenService.saveInfo(gunsToken,userInfo));

    }

//    @PostMapping("login")
//    public R<?> login(@RequestBody LoginBody form)
//    {
//        // 用户登录
//        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
//        // 获取登录token
//        return R.ok(tokenService.createToken(userInfo));
//    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();

    }


    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }
}
